package dao.impl;

import java.util.List;

import dao.TodoDao;
import entity.Todo;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class TodoDaoImpl implements TodoDao {

	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void deleteTodoById(Integer id) {
		Session session=sessionFactory.getCurrentSession();
		Todo todo=(Todo) session.get(Todo.class, id);
		if(todo!=null){
			session.delete(todo);
		}

	}

	public void insertTodo(Todo todo) throws Exception {
		Session session=sessionFactory.getCurrentSession();
		session.save(todo);
	}

	public List<Todo> selectAllTodosByPb(int pageNo,int pageSize){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Todo order by id asc");
		query.setFirstResult((pageNo-1)*pageSize);
		query.setMaxResults(pageSize);
		List<Todo> list=query.list();
		return list;
	}

	public Todo selectTodoById(Integer id) throws Exception {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Todo where id = ?");
		List<Todo> list = query.setInteger(0, id).list();
		return list.get(0);
	}
	
	public List<Todo> selectTodoByName(String name) {
		Session session = sessionFactory.getCurrentSession();
		Query query=session.createQuery("select  count(*) from Todo where name=?");
		List<Todo> list = query.setString(0, name).list();
		return list;
	}

	public void updateTodo(Todo todo) throws Exception {
		Session session = sessionFactory.getCurrentSession();
		session.update(todo);

	}

	public int selectCount() {
		Session session=sessionFactory.getCurrentSession();
		Query query = session.createQuery("select count(*) from Todo");
		Long count = (Long) query.uniqueResult();
		return count.intValue();
	}

}
